/*
 * Copyright 2008 Wilfred Springer
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.agilejava.javaone.tools;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.kohsuke.args4j.Option;

import com.agilejava.javaone.Element;
import com.agilejava.javaone.ItemizedList;
import com.agilejava.javaone.ListItem;
import com.agilejava.javaone.Para;
import com.agilejava.javaone.ScheduleBuilderSessionCatalog;
import com.agilejava.javaone.ScheduledSession;
import com.agilejava.javaone.Session;
import com.agilejava.javaone.SessionCatalog;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.HtmlTextConstruct;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.extensions.When;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

public class GcalSchedulerTool extends AbstractJavaOneTool {

    private static DateTimeFormatter FORMAT = DateTimeFormat
            .forPattern("yyyy-MM-dd'T'HH:mm:ssZZ");

    @Option(name = "-gu", usage = "Google calendar username.", required = true)
    private String gcalUsername;

    @Option(name = "-gp", usage = "Google calendar password.", required = true)
    private String gcalPassword;

    @Option(name = "-gid", usage = "Google calendar id.", required = true)
    private String gcalId;

    @Option(name = "-a", usage = "All sessions. (As opposed to just your own.)")
    private boolean allSessions;

    public final static void main(String[] args) {
        execute(new GcalSchedulerTool(), args);
    }

    @Override
    public void execute(ErrorHandler handler) {
        List<? extends Session> sessions = getSessions();
        CalendarService service = new CalendarService("agilejava-j108-0.1");
        try {
            service.setUserCredentials(gcalUsername, gcalPassword);
            URL url = new URL("http://www.google.com/calendar/feeds/" + gcalId
                    + "/private/full");
            for (Session session : sessions) {
                ScheduledSession scheduled = (ScheduledSession) session;
                if (!allSessions && scheduled.isRegistered()) {
                    System.out.println("Scheduling " + scheduled.getId());
                    CalendarEventEntry entry = new CalendarEventEntry();
                    entry
                            .setTitle(new PlainTextConstruct(scheduled
                                    .getTitle()));
                    entry.setContent(new HtmlTextConstruct(
                            getContent(scheduled)));
                    When time = new When();
                    String start = getDateRepresentation(scheduled
                            .getInterval().getStart());
                    String end = getDateRepresentation(scheduled.getInterval()
                            .getEnd());
                    time.setStartTime(DateTime.parseDateTime(start));
                    time.setEndTime(DateTime.parseDateTime(end));
                    entry.addTime(time);
                    service.insert(url, entry);
                }
            }
            // CalendarEventEntry myEntry = new CalendarEventEntry();
            //
            // myEntry.setTitle(new PlainTextConstruct("Tennis with Beth"));
            // myEntry.setContent(new PlainTextConstruct(
            // "Meet for a quick lesson."));
            //
            // DateTime startTime = DateTime
            // 2008-05-06T10:50:00+01:00
            // .parseDateTime("2006-04-17T15:00:00-08:00");
            // DateTime endTime = DateTime
            // .parseDateTime("2006-04-17T17:00:00-08:00");
            // When eventTimes = new When();
            // eventTimes.setStartTime(startTime);
            // eventTimes.setEndTime(endTime);
            // myEntry.addTime(eventTimes);
            //
            // // Send the request and receive the response:
            // CalendarEventEntry insertedEntry = service.insert(url, myEntry);
            // System.out.println(entry.getTitle().getPlainText());
        } catch (AuthenticationException e) {
            handler.error(e.getMessage());
        } catch (MalformedURLException e) {
            handler.error(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            handler.error(e.getMessage());
        } catch (ServiceException e) {
            e.printStackTrace();
            handler.error(e.getMessage());
        }
    }

    private String getContent(ScheduledSession scheduled) {
        StringBuilder builder = new StringBuilder();
        for (Element element : scheduled.getSummaryElements()) {
            if (element.isPara()) {
                builder.append("<p>");
                builder.append(((Para) element).getText());
                builder.append("</p>");
            } else {
                builder.append("<ul>");
                for (ListItem item : ((ItemizedList) element).getItems()) {
                    builder.append("<li>");
                    builder.append(item.getText());
                    builder.append("</li>");
                }
                builder.append("</ul>");
            }
        }
        return builder.toString();
    }

    private String getDateRepresentation(org.joda.time.DateTime dateTime) {
        return FORMAT.print(dateTime);
    }

    @Override
    public String getName() {
        return "j108gcal";
    }

    @Override
    public SessionCatalog getCatalog() {
        return new ScheduleBuilderSessionCatalog(getUsername(), getPassword(),
                20);
    }

}
